const {src,dest,series,parallel}  = require('gulp')
const path = require('path')
const webpackStream = require('webpack-stream')
const gulpSass = require('gulp-sass')
const rev = require('gulp-rev')
const revCollector = require('gulp-rev-collector')

//拷贝 index.html 到dist目录下
function copyHtml(){
    return src('./*.html')
        .pipe(dest('./dist/'))
}
//拷贝 libs 到dist目录下
function copyLibs(){
    return src('./src/libs/**/*')
        .pipe(dest('./dist/libs'))
}
//拷贝 libs 到dist目录下
function copyImages(){
    return src('./src/images/**/*')
        .pipe(dest('./dist/images'))
}
//拷贝 libs 到dist目录下
function copyIcons(){
    return src('./src/icons/**/*')
        .pipe(dest('./dist/icons'))
}

//编译JS模块
function packJs(){
    return src('./src/**/*')
        .pipe(webpackStream({
            mode:'production',
            entry:{
                app:'./src/app.js'
            },
            output:{
                filename:'[name].js', //[name] = app
                path:path.resolve(__dirname,'./dist') //__dirname是当前打开文件所在的物理路径
            },
            //将ES6-ES8 代码转换成 ES5
            module:{
                rules:[
                    {
                        test:/\.js$/,
                        exclude:/node_modules/,
                        use:{
                            loader:'babel-loader',
                            options:{
                                presets:['@babel/preset-env'],
                                plugins: ['@babel/plugin-transform-runtime']
                            }
                        }   
                    },
                    {
                        test:/\.html$/,
                        loader:'string-loader'
                    }
                ]
            }
        }))
        .pipe(rev())
        .pipe(dest('./dist/scripts'))
        .pipe(rev.manifest())
        .pipe(dest('./rev/scripts'))
}

//编译Css模块
function packCss(){
    return src('./src/styles/app.scss')
        .pipe(gulpSass().on('error',gulpSass.logError))
        .pipe(rev())
        .pipe(dest('./dist/styles'))
        .pipe(rev.manifest())
        .pipe(dest('./rev/styles'))
}

//将rev设置好js,css文件名的文件 连接到html
function revCollect(){
    return src(['./rev/**/*.json','./dist/*.html'])
        .pipe(revCollector())
        .pipe(dest('./dist'))
}

exports.default = series(parallel(packJs,packCss,copyLibs,copyImages,copyIcons),copyHtml,revCollect)